package com.vframework.cms.document.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.util.FileUtil;
import com.util.StringUtil;
import com.util.UUIDUtil;
import com.util.UploadUtil;
import com.vframework.base.exception.BaseException;
import com.vframework.base.service.impl.BaseServiceImpl;
import com.vframework.cms.document.mapper.DocumentMapper;
import com.vframework.cms.document.model.DocumentBean;
import com.vframework.cms.document.service.DocumentService;
import com.vframework.common.constant.BusinessConstant;

@Service
public class DocumentServiceImpl extends BaseServiceImpl implements DocumentService {

    @Autowired
    private DocumentMapper documentMapper;
    
    @Override
    public Integer getCount(Map<String, Object> paramMap) throws BaseException {
        return documentMapper.getCount(paramMap);
    }
    
    @Override
    public List<DocumentBean> getList(Map<String, Object> paramMap) throws BaseException {
        return documentMapper.getList(paramMap);
    }

    @Override
    public List<DocumentBean> getParents(String parentId) throws BaseException {
        return documentMapper.getParents(parentId);
    }

    @Override
    public DocumentBean getParentByPath(String path) throws BaseException {
        //是否带点，带点证明带文件名
        int hasDot = path.indexOf(".");
        path = path.replace(BusinessConstant.FILE_STORE_PREFIX, "");
        String[] paths = path.split("\\W+");
        path = "";
        for (int i = 0, j = paths.length; i < j; i++) {
            if ("".equals(paths[i])) {
                continue;
            }
            //如果带文件名，将文件名去掉
            if (hasDot >= 0 && i >= j - 2) {
                continue;
            }
            path += (paths[i] + "%");
        }
        path = path.substring(0, path.length() - 1);
        DocumentBean documentBean = documentMapper.getParentByPath(BusinessConstant.FILE_STORE_PREFIX + "%" + path);
        if (documentBean == null) {
            int preLeven = path.lastIndexOf("%");
            String newPath = "";
            if (preLeven > -1)
            newPath = path.substring(0, preLeven);
            if (preLeven < 0 || newPath.endsWith(BusinessConstant.ATTACHMENT_DIR)) {
                DocumentBean topDocumentBean = new DocumentBean();
                topDocumentBean.setParentId("0");
                topDocumentBean.setFileName(path.substring(preLeven + 1, path.length()));
                topDocumentBean.setFileSize("0");
                topDocumentBean.setPath(BusinessConstant.FILE_STORE_PREFIX + File.separator + path.replace("%", File.separator));
                topDocumentBean.setUid(UUIDUtil.getUUID());
                topDocumentBean.setFileType("folder");
                insert(topDocumentBean);
                return topDocumentBean;
            }
            DocumentBean parentDocumentBean = getParentByPath(newPath);
            DocumentBean newDocumentBean = new DocumentBean();
            newDocumentBean.setParentId(parentDocumentBean.getFileId());
            newDocumentBean.setFileName(path.substring(preLeven + 1, path.length()));
            newDocumentBean.setFileSize("0");
            newDocumentBean.setPath(BusinessConstant.FILE_STORE_PREFIX + File.separator + path.replace("%", File.separator));
            newDocumentBean.setUid(UUIDUtil.getUUID());
            newDocumentBean.setFileType("folder");
            insert(newDocumentBean);
            return newDocumentBean;
        }
        return documentBean;
    }
    
    public int updateRootPath(String fileId) throws BaseException {
        return documentMapper.updateRootPath(fileId);
    }
    
    @Override
    public DocumentBean getById(String fileId) throws BaseException {
        return documentMapper.getById(fileId);
    }

    @Override
    public DocumentBean getByUId(String uid) throws BaseException {
        return documentMapper.getByUId(uid);
    }

    @Override
    public Integer insert(DocumentBean documentBean) throws BaseException {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("param_path", documentBean.getPath());
        Integer count = documentMapper.getCount(paramMap);
        if (count != null && count > 0) {
            throw new BaseException("路径已经存在，请更换");
        }
        Integer res = documentMapper.insertDocument(documentBean);
        //更新rootPath
        updateRootPath(documentBean.getFileId());
        //插入成功
        if (res > 0) {
            //创建文件夹
            if ("folder".equals(documentBean.getFileType())) {
                if ("1".equals(documentBean.getPermission())) {
                    //私有文件保存路径
                    FileUtil.createFolder(UploadUtil.replaceFilePrivatePath(documentBean.getPath()));
                } else {
                    //公共文件保存路径
                    FileUtil.createFolder(UploadUtil.replaceFilePath(documentBean.getPath()));
                }
            }
        }
        return res;
    }

    /**
     * Create At:   2017年10月11日
     * @author   ztshan
     * @param    
     * @return    
     * @description  更新实际操作上传图片--删除旧图片--重命名新图片为旧图片名，更新图片大小
     */
    @Override
    public Integer update(DocumentBean documentBean) throws BaseException {
        DocumentBean oldDocumentBean = null;
        if (!StringUtil.isEmpty(documentBean.getFileId())) {
            oldDocumentBean = getById(documentBean.getFileId());//查询数据库保存的数据内容
        }
        if (oldDocumentBean != null) {
            UploadUtil.deleteFile(oldDocumentBean.getPath());//删除旧图片
            FileUtil.renameFile(UploadUtil.replaceFilePath(documentBean.getPath()), 
                    UploadUtil.replaceFilePath(documentBean.getPath().replace(documentBean.getFileName(), oldDocumentBean.getFileName()))); //重命名新图片
        }
        return documentMapper.updateDocument(documentBean);
    }

    @Override
    public Integer delete(Map<String, Object> paramMap) throws BaseException {
        List<DocumentBean> list = getList(paramMap);
        List<DocumentBean> folderList = new ArrayList<DocumentBean>();
        //文件夹下是否有文件或文件夹
        for (DocumentBean documentBean : list) {
            if ("folder".equals(documentBean.getFileType())) {
                folderList.add(documentBean);
            }
        }
        //要删除的内容中有文件夹
        if (folderList.size() != 0) {
            String[] parent_ids = new String[folderList.size()];
            for (int i = 0; i < folderList.size(); i++) {
                parent_ids[i] = folderList.get(i).getFileId();
            }
            paramMap.put("oldIds", paramMap.get("ids"));
            paramMap.remove("ids");
            paramMap.put("parent_ids", parent_ids);
            List<DocumentBean> childrenList = getList(paramMap);
            //文件夹中包含内容，返回-1
            if (childrenList != null && childrenList.size() > 0) {
                return -1;
            }
            //还原paramMap中参数
            paramMap.put("ids", paramMap.get("oldIds"));
            paramMap.remove("parent_ids");
        }
        Integer res = documentMapper.deleteDocument((String[])paramMap.get("ids"));
        //数据库删除成功，删除服务器上的文件
        if (res > 0) {
            for (DocumentBean dBean: list) {
                UploadUtil.deleteFile(dBean.getPath());
            }
        }
        return res;
    }

}
